import { trigger, state, transition, style, animate } from '@angular/animations';
import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';

export class PaginationList<T> {
    datas: Array<T>;
    total: number;
    pageNo: number;
    pageSize: number;
}

const ngForFlyInAnimation = trigger(
    'ngForFlyInAnimation', [
        state('in', style({ opacity: 1, transform: 'translateX(0)' })),
        transition('void => *', [
            style({
                opacity: 0,
                transform: 'translateX(-100%)'
            }),
            animate('0.3s ease-in')
        ]),
        transition('* => void', [
            animate('0.2s 0.1s ease-out', style({
                opacity: 0,
                transform: 'translateX(100%)'
            }))
        ])
    ]
);

@Component({
    selector: 'cmb-pagination',
    templateUrl: './pagination.component.html',
    styleUrls: ['./pagination.component.scss'],
    // changeDetection: ChangeDetectionStrategy.OnPush,
    animations: [ngForFlyInAnimation]
})
export class PaginationComponent implements OnInit {

    list = [];
    isLoading = false;
    private pageNo = -1;

    @Input()
    set paginationList(paginationList: PaginationList<any>) {
        this.isLoading = false;
        if (paginationList) {
            if (paginationList.datas) {
                if (paginationList.pageNo !== this.pageNo) {
                    this.pageNo = paginationList.pageNo;
                    this.list.push(...paginationList.datas);
                    // paginationList.datas.forEach((item, index) => {
                    //     setTimeout(() => {
                    //         this.list.push(item);
                    //         this.ref.markForCheck();
                    //     }, index * 100);
                    // });
                }
            }
            this.isLoadAll = this.list.length >= paginationList.total;
            if (this.isLoadAll) {
                this.onLoadedAll.emit(this.isLoadAll);
            }
        }
    }

    @Input() inputTpl;

    @Input() emptyDataTpl = null;

    @Input() scrollWindow = true;

    @Input() infiniteScrollDistance = 0.3;

    @Input() infiniteScrollThrottle = 300;

    @Input() isLoadAll = false;

    @Output() onLoadedAll = new EventEmitter<boolean>();

    @Output() onLoadData = new EventEmitter<boolean>();

    constructor(private ref: ChangeDetectorRef) { }

    ngOnInit() {
    }

    onScrollDown() {
        this.isLoading = true;
        this.onLoadData.emit();
    }
}
